<?php

namespace app\shopapi\model\lakala;


use app\admin\model\Config;
use app\common\model\User;
use app\shopapi\model\Shop;
use fast\Http;
use think\Log;

require_once ROOT_PATH.'extend/lakala/sdk/com/fds/FdsSdk.php';
//交易接口
class Pay
{
    public $appid = '7262709374893195265';

    public $DSAPublicKeyPath = ROOT_PATH.'extend/cert2/cloud_dsa_public.pem';

    public $DSAPrivateKeyPath = ROOT_PATH.'extend/cert2/dsa_private_key.pfx';

    public $RSAPublicKeyPath = ROOT_PATH.'extend/cert2/cloud_rsa_public.pem';

    public $RSAPrivateKeyPath = ROOT_PATH.'extend/cert2/rsa_private_key.pfx';

    public $gatewayUrl = 'https://moneyconnect.lakala.com/service/soa';

    public function __construct()
    {
        //应用编号，需修改
        \FdsSdk::setAppId($this->appid);

        \FdsSdk::setApiVersion("3.0");

        \FdsSdk::setDSAKey($this->DSAPublicKeyPath, $this->DSAPrivateKeyPath, "965555");

        \FdsSdk::setRSAKey($this->RSAPublicKeyPath, $this->RSAPrivateKeyPath, "965555");
    }


    //商户提现
    public function withdraw($shop_id,$amount)
    {
        $shop_info = Shop::get($shop_id);
        \FdsSdk::setServerUrl($this->gatewayUrl);
        $memberInfo = \FdsSdk::getService()->memberMerchantInfo($shop_info);
        $out_order_no = date("YmdHis") . sprintf("%08d", $shop_id) . mt_rand(1000, 9999);
        $request = \think\Request::instance();
        $back_url = $request->root(true) . '/shopapi/auth/notify';
        $bank_card_no = '';
        $data = [
            'member_no'=>$memberInfo['member_no'],
            'out_order_no'=>$out_order_no,
            'amount'=>$amount,
            'back_url'=>$back_url,
            'billing_fee'=>0,
            'bank_card_no'=>$bank_card_no
        ];
        $result = \FdsSdk::getService()->withdraw($data);
        if ($result['status']=='OK'){
            return $result['result'];
        } else {
            throw new \Exception($result['message']);
        }
    }


    //公众号/服务窗/小程序支付下单,测试pay_method用QR_CODE
    public function orderConsume($data)
    {
        \FdsSdk::setServerUrl($this->gatewayUrl);

        $out_order_no = date("YmdHis") . sprintf("%08d", $data['shop_id']) . mt_rand(1000, 9999);

        $shop_info = Shop::get($data['shop_id']);

        $user_info = User::get($data['user_id']);
        $config = Config::get(1);

        $data_param = [
            //'buyer_member_no'=>$buyer_member_no,
            //'seller_member_no'=>$data['seller_member_no'],
            'seller_member_no'=>$shop_info['member_no'],
            'out_order_no'=>$out_order_no,
            'amount'=>$data['amount'],
            'terminal_ip'=>$data['terminal_ip'],
            'back_url'=>$data['back_url'],
            'order_name'=>$data['order_name'],
            'split_mode'=>$data['split_mode'],
            'pay_method'=>[
                'JSAPI'=>[
                    'amount'=>$data['amount'],
                    'mch_appid'=>$config['mini_app_id'],
                    'openid'=>$user_info['wechat_open_id'],
                    'mode'=>'wxpay',
                    //'front_url'=>$front_url,
                    //'front_fail_url'=>$front_fail_url,
                    //'goods_detail'=>[],
                    'term_base_station'=>'00+LAC:6361+CID:58130',
                    'term_loc'=>'+39.9075/-116.3972',
                        //+37.123456789/-121.123456789
                ],
                /*'GATEWAY'=>[
                    'amount'=>$data['amount'],
                    'merchant_no'=>$shop_info['checkstand_merchant_no'],
                    'member_no'=>$shop_info['member_no'],
                    'product_name'=>$data['order_name'],
                    'support_refund'=>1,
                    'counter_param'=>[
                        'pay_mode'=>'WECHAT'
                    ]
                ]*/
            ],

        ];
        if (isset($data['split_rule_data']))$data_param['split_rule_data'] = $data['split_rule_data'];

        $result = \FdsSdk::getService()->orderConsume($data_param);

        if ($result['status']=='OK'){
            return $result['result'];
        } else {
            throw new \Exception($result['message']);
        }
    }


    //退款
    public function refund($order_no,$out_request_no,$refund_amount,$pay_seq_no,$member_no)
    {
        \FdsSdk::setServerUrl($this->gatewayUrl);

        $data = [
            'order_no'=>$order_no,
            'out_request_no'=>$out_request_no,
            'refund_amount'=>(int)($refund_amount*100),
            'pay_seq_no'=>$pay_seq_no,
            /*'refund_rule'=>[
                [
                    'member_no'=>$member_no,
                    'amount'=>(int)($refund_amount*100),
                ]
            ]*/
        ];

        $result = \FdsSdk::getService()->refund($data);
        if ($result['status']=='OK'){
            //return $result['result'];
            return [
                'code'=>1,
                'data'=>$result['result'],
                //'msg'=>$result['message']
            ];
        } else {
            return [
                'code'=>0,
                'msg'=>$result['message']
            ];
            //throw new \Exception($result['message']);
        }
    }

    //分账撤销
    public function splitRevoke()
    {
        \FdsSdk::setServerUrl($this->gatewayUrl);
        $order_no = '7265559765354450944';
        $split_seq_no = '7265559809667837952';
        $amount = 3.96;

        $result = \FdsSdk::getService()->splitRevoke($order_no,$split_seq_no,$amount);
        dump($result);die;
        if ($result['status']=='OK'){
            return $result['result'];
        } else {
            throw new \Exception($result['message']);
        }
    }


    //查询支付状态
    public function getOrderStatus($order_no,$out_order_no)
    {
        \FdsSdk::setServerUrl($this->gatewayUrl);

        $data = [
            'order_no'=>$order_no,
            'out_order_no'=>$out_order_no,
        ];
        $result = \FdsSdk::getService()->getOrderStatus($data);
        if ($result['status']=='OK'){
            return $result['result'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //余额
    public function getBalance($member_no)
    {
        \FdsSdk::setServerUrl($this->gatewayUrl);

        $result = \FdsSdk::getService()->getBalance($member_no);
        if ($result['status']=='OK'){
            return $result['result'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //查询收入金额支出
    public function getBalancePage($member_no,$start_time,$end_time)
    {
        \FdsSdk::setServerUrl($this->gatewayUrl);

        $result = \FdsSdk::getService()->getBalancePage($member_no,$start_time,$end_time);
        if ($result['status']=='OK'){
            return $result['result'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //完成订单（确权分账）
    public function orderComplete($order_no,$member_no,$out_request_no,$split_amount,$split_list)
    {
        \FdsSdk::setServerUrl($this->gatewayUrl);

        $data = [
            'order_no'=>$order_no,
            'member_no'=>$member_no,
            'out_request_no'=>$out_request_no,
            'split_amount'=>$split_amount,
            'split_rule_data'=>[
                'split_list'=>$split_list
            ]
        ];
        Log::error('分账参数:'.json_encode($data,320));
        //dump($data);die;
        $result = \FdsSdk::getService()->orderComplete($data);
        //dump($result);die;

        if ($result['status']=='OK'){
            //return $result['result'];
            return [
                'code'=>1,
                'data'=>$result['result'],
                //'msg'=>$result['message']
            ];
        } else {
            return [
                'code'=>0,
                'msg'=>$result['message']
            ];
            //throw new \Exception($result['message']);
        }
    }

    //完成订单（确权分账）
    public function ceshiOrderComplete()
    {
        \FdsSdk::setServerUrl($this->gatewayUrl);

        $split_list = [
            [
                'member_no'=>'7275030652950458368',
                'amount'=>1000
            ],
            [
                'member_no'=>'7262709383570984960',
                'amount'=>0
            ]
        ];

        $data = [
            'order_no'=>'7275065802925182976',
            'member_no'=>'7275030652950458368',
            'out_request_no'=>'20241218163500000000124279',
            'split_amount'=>1000,
            'split_rule_data'=>[
                'split_list'=>$split_list
            ]
        ];
        //dump($data);die;
        $result = \FdsSdk::getService()->orderComplete($data);

        if ($result['status']=='OK'){
            //return $result['result'];
            return [
                'code'=>1,
                'data'=>$result['result'],
                //'msg'=>$result['message']
            ];
        } else {
            return [
                'code'=>0,
                'msg'=>$result['message']
            ];
            //throw new \Exception($result['message']);
        }
    }
}